package com.pingan.cashier.service.impl;

import com.pingan.cashier.common.config.Constants;
import com.pingan.cashier.dal.entity.PayOrder;
import com.pingan.cashier.dal.mapper.PayOrderMapper;
import com.pingan.cashier.service.CallbackService;
import com.pingan.cashier.service.dto.BaseCallBackDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import static com.pingan.cashier.common.config.Constants.PAY_STATUS_ALIPAY_PAY;
import static com.pingan.cashier.common.config.Constants.PAY_STATUS_ALIPAY_SUCCESS;

/**
 * 支付宝回调实现
 */
@Slf4j
@Service
public class AlipayCallbackServiceImpl implements CallbackService {

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void callback(BaseCallBackDTO baseCallBackDTO) {

        // 一系列合法性/权限校验

        PayOrder payOrder = payOrderMapper.getByTradeNo(baseCallBackDTO.getTradeNo(),
                baseCallBackDTO.getPayType());
        if (payOrder == null) {
            throw new RuntimeException("未知交易号" + baseCallBackDTO.getTradeNo());
        }
        Integer payStatus;
        // 支付交易中
        if (PAY_STATUS_ALIPAY_PAY.equals(baseCallBackDTO.getTradeStatus())) {
            payStatus = 0;
        }
        // 支付成功
        else if (PAY_STATUS_ALIPAY_SUCCESS.equals(baseCallBackDTO.getTradeStatus())) {
            payStatus = 1;
        }
        // 支付失敗
        else {
            payStatus = 2;
        }
        log.info("pay_result_tradeNo={}, status={}", baseCallBackDTO.getTradeNo(), baseCallBackDTO.getTradeStatus());
        PayOrder update = new PayOrder();
        update.setResult(payStatus);
        update.setResultCode(baseCallBackDTO.getTradeStatus());
        update.setUpdateTime(new Date());
        update.setOutTradeNo(baseCallBackDTO.getTradeNo());
        update.setPayType(baseCallBackDTO.getPayType());

        int result = payOrderMapper.updateOrder(update);
        if(result == 0){
            throw new RuntimeException("更新數據庫失敗" + baseCallBackDTO.getTradeNo());
        }
    }

    @Override
    public boolean supportPayType(Integer payType) {
        return Constants.PAY_TYPE_ZFB.equals(payType);
    }
}
